package com.dreamstations.changshads.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.dreamstations.changshads.R;

/**
 * Created by 7YHong on 2016/6/12.
 * 使用setupWithViewPager来添加当页面切换时的选中点切换
 * View的可选参数：
 * app:resource="@drawable/vp_indicator"    小圆点的drawable
 */
public class Slide_Indicator extends LinearLayout{
    View[] views;
    int lastsSlected=0;


    int indicatorId=android.R.drawable.button_onoff_indicator_off;
    public Slide_Indicator(Context context) {
        this(context,null);
    }

    public Slide_Indicator(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public Slide_Indicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.HORIZONTAL);
        //得到Indicator的图标
        if (attrs!=null){
            TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.slide_indicator);
            indicatorId=ta.getResourceId(R.styleable.slide_indicator_resource,R.drawable.dot);
            ta.recycle();
        }
        initIndicator(3);
    }

    public void setIndicatorId(int indicatorId) {
        this.indicatorId = indicatorId;
    }

    private void setSelected(int index){
        if (index==lastsSlected) return;
        views[index].setSelected(true);
        views[lastsSlected].setSelected(false);
        lastsSlected=index;
    }

    private void initIndicator(final int count){
        if (views!=null){
            removeAllViews();
            views=null;
        }
        views=new View[count];
        for (int i=0;i<count;i++){
            ImageView v=new ImageView(getContext());
            v.setBackgroundResource(indicatorId);
            v.setAdjustViewBounds(true);
            LayoutParams lp=new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(8,8,8,8);
            v.setLayoutParams(lp);
            addView(v);
            views[i]=v;
        }
        views[0].setSelected(true);
    }

    public void setupWithViewPager(ViewPager viewPager){
        initIndicator(viewPager.getAdapter().getCount());

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
}
